package com.dragon.user.dao.enums;

import com.baomidou.mybatisplus.core.enums.IEnum;
import org.springframework.util.ReflectionUtils;

import java.io.Serializable;
import java.lang.reflect.Field;

public interface IBaseEnum<T extends Serializable> extends IEnum<Integer> {

	String DEFAULT_CODE_NAME = "code";

	String DEFAULT_DESC_NAME = "desc";

	default int getCode() {
		Field field = ReflectionUtils.findField(this.getClass(), DEFAULT_CODE_NAME);
		if (field == null)
			throw new IllegalArgumentException();
		try {
			field.setAccessible(true);
			return Integer.parseInt(field.get(this).toString());
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

//	@JsonValue
	default String getDesc() {
		Field field = ReflectionUtils.findField(this.getClass(), DEFAULT_DESC_NAME);
		if (field == null)
			return null;
		try {
			field.setAccessible(true);
			return field.get(this).toString();
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

	static <T extends Enum<T>> T codeOfEnum(Class<T> enumClass, Integer code) {
		if (code == null)
			throw  new IllegalArgumentException("IBaseEnum code should not be null");
		if (enumClass.isAssignableFrom(IBaseEnum.class))
			throw new IllegalArgumentException("illegal IBaseEnum type");
		T[] enums = enumClass.getEnumConstants();
		for (T t: enums) {
			IBaseEnum iBaseEnum = (IBaseEnum)t;
			if (iBaseEnum.getCode() == (code))
				return (T) iBaseEnum;
		}
		throw new IllegalArgumentException("cannot parse integer: " + code + " to " + enumClass.getName());
	}

	String getDescription();
}
